package com.yunxiangyue.musicplayer

import android.app.*
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Binder
import android.os.IBinder
import android.util.Log
//import com.yunxiangyue.Operate
import com.yunxiangyue.app.R
import com.yunxiangyue.logger.Logger
import java.io.File
import java.util.*
import kotlin.collections.ArrayList
var isBind:Boolean = false
class MusicService : Service() {
    val notiyID = 1
    val mediaPlayer = MediaPlayer()
//    var flag = true
    var process = 0
    var binder = musicBinder()
    val channelId = "weibo channel"
    var count = 1
    var aixinCount = 0
    var current = 0
    var musicPathList = mutableListOf<String>()
    var musicNameList = mutableListOf<String>()
    var musicSingerList = mutableListOf<String>()
    private var fileUri:Uri? = null
    private var musicName:String? = ""
    private var musicList:ArrayList<Music> = ArrayList()
    private val tag = "MusicService"
    var isPause:Boolean = true
    var isPrepared = false




    inner class musicBinder : Binder() {

        fun setCurrentDuration(process: Int): Boolean {
            return if (isMediaPlayerReady()) {
                mediaPlayer.seekTo(process)
                true
            } else {
                Logger.error(tag, "cant set process when media player not ready")
                false
            }
        }

        fun getCurrentMusicName(): String {
            return try {
                musicNameList.get(current)
            } catch (e: IndexOutOfBoundsException) {
                Log.e(tag, "error when get music name e:$e, now list size ${musicNameList.size}")
                "null"
            }
        }
        fun getCurrentMusicSinger():String {
            return try {
                musicSingerList.get(current)
            }catch (e:IndexOutOfBoundsException){
                Log.d(tag,"error when get music name e:$e, now list size ${musicSingerList.size}")
                "null"
            }
        }
        fun getMediaPlayer(): MediaPlayer {
            return mediaPlayer
        }

        fun isMediaPlayerReady(): Boolean {
            return isPrepared
        }

        fun getMusicService(): MusicService {
            return this@MusicService
        }

        fun setMusicList(musicList: ArrayList<Music>) {
            for(music:Music in musicList){
                musicNameList.add(music.musicName)
                musicSingerList.add(music.play)
            }
        }

        fun startNewMusic(loc: Int, fileUri: Uri){
            Logger.debug(tag, "musicList size = ${musicList.size}, musicName = ${musicList[loc].musicName}, file uri: $fileUri")

            //获取当前音乐列表所在位置
            current = loc
            Logger.debug(tag, "startCommand music size is ${fileUri.path?.let { it1 -> File(it1).length() }}")

            prepareMusicAndPlay(fileUri)
            Log.d(tag,"musicNameList ："+musicNameList)
            Log.d(tag,"musicSingerList :"+musicSingerList)
        }
    }

    override fun onBind(p0: Intent?): IBinder? {
        return binder
    }

    override fun onCreate() {
        super.onCreate()

        mediaPlayer.setOnPreparedListener {
            Logger.debug(tag, "mediaPlayer ready, musicName = $musicName, duration = ${it.duration}")
            isPrepared = true
            isPause = false
            it.start()
        }
        mediaPlayer.setOnCompletionListener {
            Logger.debug(tag, "complete and play next music, now dur = ${it.currentPosition}, dur = ${it.duration}")
//            if(current == musicNameList.size - 1){
//                current = 0
//            }else{
//                current ++
//            }
//            //当歌曲的时长获取成功后
//            Logger.debug(tag,"current : $current")
//            isPause = true
//            aixinCount = 0
        }
        setNotify()
    }

    fun playMusic() {
        mediaPlayer.start()
        isPause = false
    }

    fun pauseMusic() {
        mediaPlayer.pause()
        isPause = true
    }

    fun prepareMusicAndPlay(uri: Uri) {
        //如果有音乐在播放  将音乐暂停并重置mediaplayer清理残余文件
        try {
            mediaPlayer.stop()
            mediaPlayer.reset()

            isPrepared = false

            // 设置数据源为临时文件的URI
            mediaPlayer.setDataSource(this, uri)
            Logger.debug(tag,"setDataResource设置的音乐uri为:$uri  $musicName")
            // 开始播放
            mediaPlayer.prepareAsync()
            setNotify()
//            mediaPlayer.setOnPreparedListener { mp ->
//                // 准备完成，开始播放
//                mp.start()
//            }
//            mediaPlayer.setOnErrorListener { mp, what, extra ->
//                // 发生错误，处理错误情况
//                true // 返回true表示错误已经被处理，不需要系统默认的错误处理
//            }
        } catch (e: Exception) {
            Logger.error(tag, "catch exception when prepare music, e: ${e.printStackTrace()}")
            // 处理错误
        }
    }

    private fun setNotify() {
//        设置通知步骤：
//        1：创建系统的通知管理器
//        2：指定通知的渠道
//        3：使用Notification.Builder创建通知
//        4：设置通知的属性和点击通知后进入的页面，使用意图
//        5：使用系统的通知管理器开启通知
        val notificationManager =
            getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val notificationChannel =
            NotificationChannel(channelId, "channel", NotificationManager.IMPORTANCE_HIGH)
        notificationManager.createNotificationChannel(notificationChannel)
        val builder = Notification.Builder(this, channelId)
        val intent = Intent(this, music_playing::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this,
            UUID.randomUUID().hashCode(), intent, PendingIntent.FLAG_IMMUTABLE
        )
        val no = builder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle("云想乐")
            .setContentText("正在播放" + musicName)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setWhen(System.currentTimeMillis())
            .build()
        startForeground(1,no)
    }

    override fun onUnbind(intent: Intent?): Boolean {
        return super.onUnbind(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        mediaPlayer.stop()
        mediaPlayer.release()
    }

}